package org.domeos.framework.api.task;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.PostConstruct;

import org.domeos.framework.api.biz.cluster.ClusterBiz;
import org.domeos.framework.api.controller.exception.ApiException;
import org.domeos.framework.api.model.cluster.Cluster;
import org.domeos.framework.api.model.cluster.related.NodeInfo;
import org.domeos.framework.api.service.cluster.ClusterService;
import org.domeos.framework.engine.k8s.NodeWrapper;
import org.domeos.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 
 * @author lixiaokai
 *
 */

@Component
public class DockerCleaner {
	
	private static AtomicBoolean started = new AtomicBoolean(false);

	private static Logger logger = LoggerFactory
			.getLogger(ProductLineUpdater.class);

	private ScheduledExecutorService scheduledExecutor = Executors
			.newScheduledThreadPool(1);
	
	@Autowired
    ClusterService clusterService;
	
	@Autowired
	ClusterBiz clusterBiz;

	@PostConstruct
	public void init() {
		if (started.compareAndSet(false, true)) {
			logger.info("init {}, start scheduled task checker.",
					ComponentMonitor.class.toString());
			scheduledExecutor.scheduleWithFixedDelay(
					new ImageAndContainerClean(), 0, 30, TimeUnit.DAYS);
		}
	}
	
	private class ImageAndContainerClean implements Runnable {
		
		@Override
		public void run() {
			logger.info("begin to clean unused docker container and image");
			List<String> url = new ArrayList<String>();
			url.add("/v1.29/containers/prune");
			url.add("/v1.29/images/prune");
			url.add("/v1.29/networks/prune");
			url.add("/v1.29/volumes/prune");
			
			String docker_port = ":5555";
			List<Cluster> clusters= clusterBiz.listClusters();
			for(Cluster c : clusters) {
				int clusterId = c.getId();
				List<NodeInfo> nodeInfoList = new ArrayList<NodeInfo>();
				try {
		            NodeWrapper nodeWrapper = new NodeWrapper().init(clusterId, null);
		            nodeInfoList = nodeWrapper.getNodeListByClusterId();
		            Collections.sort(nodeInfoList, new NodeInfo.NodeInfoListComparator());
		        } catch (Exception e) {
		            throw ApiException.wrapUnknownException(e);
		        }
				for(NodeInfo n: nodeInfoList) {
					String ip = n.getIp();
					for(String u: url) {
						String api = "http://" + ip + docker_port + u;
						Map<String, Object> params = new HashMap<String, Object>();
						if(u.equals("/v1.29/images/prune")) {
							params.put("filters", "{\"dangling\":{\"false\": true}}");
						}
						HttpClientUtil.doPost(api, params);
					}
				}
			}
			logger.info("finish clean docker container and image");
		}
	}
}
